const MdArticle = require('../models/mdArticle')
const Tag = require('../models/tag')

const setOutput = require('../tools/setOutput').setOutput

class MdArticleController {
  prefix = '' 
  getPath(name){
    return name ? `/${this.prefix}/${name}` : `/${this.prefix}`
  } 

  async add(ctx, next) {
    ctx.verifyParams({
      title: {type: 'string', required: true}
    })  
    let obj = {...ctx.request.body}  
    if (!obj.mdText) {
      obj.mdText = ''
    }
    if (!obj.mdContent) {
      obj.mdContent = ''
    }
    if (!obj.imgs) {
      obj.imgs = []
    }
    obj.createUserName = userInfo.userName
    obj.createName = userInfo.name
    obj.createId = userInfo._id
    
    const [addErr, res] = await to(new MdArticle(obj).save())
    if(addErr) return ctx.throw(500, err) 
    ctx.response.body = setOutput(res.toJSON()) 
  }

  async find(ctx, next) {
    const {page = 1, pageSize = 20, tag, title} = ctx.request.query 
   
    const tagOpts = tag && {tags: tag} || {}
    const userOpts = { createId: userInfo._id } 

    const titleReg = new RegExp(title, 'i')
    // const nameReg = new RegExp(name, 'i') 

    const total = await MdArticle.count({
      ...userOpts,
      ...tagOpts,
      title: titleReg
    })
    
    const list = await MdArticle.find({
      ...userOpts,
      ...tagOpts,
      title: titleReg
    }) 
    .populate([{path:'tags', select: 'label desc'}])
    .sort({ createdTime: 'desc' }).skip((parseInt(page) - 1) * parseInt(pageSize)).limit(parseInt(pageSize) || 5).lean()

    const slimList = list.map((item) => {
      const output = {...item}
      output.tags.forEach((tag) => {
        tag.id = tag._id
      })
      output.mdContent = output.mdContent && output.mdContent.replace(/<[^<>]+>/gi, '').slice(0, 60) || ''
      return output
    })
    const data = {
      list: slimList,
      total: total
    }
    ctx.response.body = setOutput(data, 'fetch')
  }

  async findOne(ctx, next) {
    const [err, data] = await to(MdArticle.findById(ctx.params.id).populate([{path:'tags', select: 'label desc'}]).lean()) 
    if(err || !data) return ctx.throw(500, err) 
    data.tags.forEach((tag) => {
      tag.id = tag._id
    })
    ctx.response.body = setOutput(data, 'get')
  }

  async update(ctx, next){
    ctx.verifyParams({
      id: { type: "string", required: true },
      title: { type: "string", required: true }
    })
    const obj = {...ctx.request.body}

     
    const [err, data] = await to( MdArticle.findByIdAndUpdate(obj.id, obj, { new: true }).populate([{path:'tags', select: 'label desc'}]).lean() )
     
    if(err || !data) return ctx.throw(500, err)
    data.tags.forEach((tag) => {
      tag.id = tag._id
    })
    data.mdContent = data.mdContent && data.mdContent.replace(/<[^<>]+>/gi, '').slice(0, 60) || ''
    ctx.response.body = setOutput(data, 'update')
  }

  async delete(ctx, next) {
    await MdArticle.deleteOne({ _id: ctx.params.id }) 
    ctx.response.body = {
      data: null,
      code: 0,
      msg: '成功'
    }
  }

  async groupArticleByTag(ctx, next) {  
    const arr = [
      {
        '$match': { createId: userInfo._id }
      },
      {
        '$unwind': '$tags'
      },
      {
        '$group': {
          '_id': '$tags', 
          'count': {'$sum': 1}
        }
      }
    ]
    
    const countList = await MdArticle.aggregate(arr)
    const tagList = await Tag.find().lean()
    // tagList = tagList.sort()   
    ctx.response.body = {
      data: {
        countList: countList,
        tagList: setOutput({list: tagList, total: 0}, 'fetch').data.list
      },
      code: 0,
      msg: '成功'
    }
  }


}

module.exports = new MdArticleController()